﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.Caching;
using System.Text;
using System.Threading.Tasks;

namespace MTQ.Common.Cache
{
    public class RuntimeCaching
    {
        static ObjectCache _cache = MemoryCache.Default;

        /// <summary>
        /// 添加缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="expires"></param>
        /// <param name="regionName"></param>
        public void Add<T>(string key, T value, TimeSpan? expires)
            where T: class
        {
            CacheItemPolicy policy = new CacheItemPolicy();
            if(expires != null)
                policy.AbsoluteExpiration = DateTimeOffset.Now.Add(expires.Value);

            _cache.Add(key, value, policy);
        }

        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="regionName"></param>
        /// <returns></returns>
        public T Get<T>(string key)
            where T: class
        {
            return (_cache.Get(key) as T);
        }

        /// <summary>
        /// 是否包含指定键
        /// </summary>
        /// <param name="key"></param>
        /// <param name="regionName"></param>
        /// <returns></returns>
        public bool Exists(string key)
        {
            return _cache.Contains(key);
        }

        /// <summary>
        /// 自定义条件删除
        /// </summary>
        /// <param name="expression"></param>
        /// <param name="regionName"></param>
        public void Remove(Func<KeyValuePair<string, object>, bool> expression)
        {
            var ls_keys = _cache.Where(expression).Select(x => x.Key);
            foreach (var key in ls_keys)
            {
                this.RemoveKey(key);
            }
        }

        /// <summary>
        ///  删除指定键
        /// </summary>
        /// <param name="Key"></param>
        /// <param name="regionName"></param>
        public void RemoveKey(string Key)
        {
            _cache.Remove(Key);
        }

        /// <summary>
        /// 删除所有项
        /// </summary>
        /// <param name="regionName"></param>
        public void RemoveAll(string regionName = "base")
        {
            var ls_keys = _cache.Select(x => x.Key);
            foreach (var key in ls_keys)
            {
                this.RemoveKey(key);
            }
        }

        public List<string> AllKeys
        {
            get
            {
                return _cache.Select(x => x.Key).ToList();
            }
        }

    }
}
